package com.dragon.www.haier.net;

import android.support.annotation.NonNull;

import com.dragon.www.haier.net.inter.IObserver;

import java.util.ArrayList;


/**
 * 用于观察WIFI连接的事件派发
 * Created by Administrator on 2015/8/3 17:15.
 * Email: thinkdata@163.com
 */
public abstract class AObservable {

    private final ArrayList<IObserver> mObservers = new ArrayList<IObserver>();

    public abstract void handler(Object... args);

    /**
     * 触发观察对象
     * @param args
     */
    public void notifyObservers(Object... args) {
        int size = 0;
        IObserver[] observers;
        synchronized (this) {
            size = mObservers.size();
            observers = new IObserver[size];
            mObservers.toArray(observers);
        }
        for (IObserver obs : observers) {
            obs.doWhat(this, args);
        }
    }

    /**
     * 添加
     * @param obs
     */
    public void registerObserver(@NonNull IObserver obs) {
        synchronized (mObservers) {
            if (!mObservers.contains(obs))
                this.mObservers.add(obs);
        }
    }

    public void unRegisterObserver(@NonNull IObserver obs) {
        synchronized (mObservers) {
            if (mObservers.contains(obs))
                this.mObservers.remove(obs);
        }
    }

    public void clearClazz(Class clazz) {
        synchronized (mObservers) {
            IObserver temp = null;
            for (int i=0; i < mObservers.size(); i++) {
                IObserver obs = mObservers.get(i);
                if (obs.getClass().getName().equalsIgnoreCase(clazz.getName())) {
                    temp = obs;
                }
            }
            if (temp != null) {
                mObservers.remove(temp);
            }
        }
    }

    public void clear() {
        synchronized (mObservers) {
            this.mObservers.clear();
        }
    }
}
